package com.web.exiaodao.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.entity.FranchiseTable;
import com.web.exiaodao.business.repository.FranchiseTableRepository;
import com.web.exiaodao.business.service.FranchiseTableService;
import com.web.exiaodao.remote.vo.FranchiseTableVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service("FranchiseTableService")
@Transactional(readOnly = false)
public class FranchiseTableServiceImpl extends BaseService<FranchiseTableVo> implements FranchiseTableService {

    private static final Logger LOGGER = Logger.getLogger(FranchiseTableServiceImpl.class);

    @Autowired
    private FranchiseTableRepository franchiseTableRepository;

    /**
     * 查询单条FranchiseTable信息
     * //@param tId
     *
     * @return 返回单个FranchiseTable对象
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<FranchiseTableVo> findOne(Long modelId) throws BusinessException {
        FranchiseTable obj = new FranchiseTable();
        if (modelId != 0) {
            obj = franchiseTableRepository.findByIdAndStatusNot(modelId, XaConstant.Status.delete);
        }
        XaResult<FranchiseTableVo> xr = new XaResult<>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), FranchiseTableVo.class));
            LOGGER.info("后台----->查询单个实体----->FranchiseTable");
        } else {
            xr.error(XaConstant.Message.object_not_find);
            LOGGER.info(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    /**
     * 分页查询状态非status的FranchiseTable数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象FranchiseTable集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<FranchiseTableVo>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", Operator.NE, status));
        Page<FranchiseTable> page = franchiseTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), FranchiseTable.class), pageable);
        XaResult<Page<FranchiseTableVo>> xr = new XaResult<>();
        xr.setObject(new MyPage<>(page, JSON.parseArray(JSON.toJSONString(page.getContent()), FranchiseTableVo.class)));
        LOGGER.info("后台----->分页查询实体集合（状态不等于）----->FranchiseTable");
        return xr;
    }

    /**
     * 分页查询状态status的FranchiseTable数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象FranchiseTable集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<FranchiseTableVo>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", Operator.EQ, status));
        Page<FranchiseTable> page = franchiseTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), FranchiseTable.class), pageable);
        XaResult<Page<FranchiseTableVo>> xr = new XaResult<>();
        xr.setObject(new MyPage<>(page, JSON.parseArray(JSON.toJSONString(page.getContent()), FranchiseTableVo.class)));
        LOGGER.info("后台----->分页查询实体集合（状态等于）----->FranchiseTable");
        return xr;
    }


    /**
     * 保存FranchiseTable信息
     *
     * @param model
     * @return
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<FranchiseTableVo> saveOrUpdate(FranchiseTableVo model) throws BusinessException {
        FranchiseTable obj = null;
        if (XaUtil.isNotEmpty(model.getId())) {
            obj = franchiseTableRepository.findOne(model.getId());
        } else {
            obj = new FranchiseTable();
        }
        obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
        obj.setCustomer_Name(XaUtil.isNotEmpty(model.getCustomer_Name()) ? model.getCustomer_Name() : obj.getCustomer_Name());
        obj.setCellphone(XaUtil.isNotEmpty(model.getCellphone()) ? model.getCellphone() : obj.getCellphone());
        obj.setFranchise_Unit_Name(XaUtil.isNotEmpty(model.getFranchise_Unit_Name()) ? model.getFranchise_Unit_Name() : obj.getFranchise_Unit_Name());
        obj.setFranchise_Unit_PicUrls(XaUtil.isNotEmpty(model.getFranchise_Unit_PicUrls()) ? model.getFranchise_Unit_PicUrls() : obj.getFranchise_Unit_PicUrls());
        obj.setRefuse_Reason(XaUtil.isNotEmpty(model.getRefuse_Reason()) ? model.getRefuse_Reason() : obj.getRefuse_Reason());
        obj.setAgreements(XaUtil.isNotEmpty(model.getAgreements()) ? model.getAgreements() : obj.getAgreements());
        obj = franchiseTableRepository.save(obj);
        XaResult<FranchiseTableVo> xr = new XaResult<>();
        xr.setObject(JSON.parseObject(JSON.toJSONString(obj), FranchiseTableVo.class));
        LOGGER.info("后台新增或编辑数据成功！");
        return xr;
    }

    /**
     * 修改FranchiseTable状态，可一次修改多条   3删除  -1锁定  1正常
     *
     * @param userId
     * @param modelIds
     * @param status
     * @return 返回FranchiseTable对象
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<FranchiseTableVo> multiOperate(
            String modelIds, Integer status) throws BusinessException {
        XaResult<FranchiseTableVo> xr = new XaResult<>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                FranchiseTable obj = franchiseTableRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setStatus(status);
                    obj = franchiseTableRepository.save(obj);
                }
            }
        }
        LOGGER.info("批量修改数据状态成功！");
        return xr;
    }

    /**
     * 修改FranchiseTable审批状态，单吃审核，审核状态(1:待审核(默认) 2：审核通过 3：审核拒绝)
     *
     * @param modelIds
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<FranchiseTableVo> multiOperatefranchiseState(
            String modelIds, Integer franchise_State, String refuse_Reason) {
        XaResult<FranchiseTableVo> xr = new XaResult<>();
        if (franchise_State == null) {
            franchise_State = XaConstant.Status.invalid;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                FranchiseTable obj = franchiseTableRepository.findByIdAndStatusNot(Long.parseLong(id), franchise_State);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setFranchise_State(franchise_State);
                    obj.setRefuse_Reason(refuse_Reason);
                    obj = franchiseTableRepository.save(obj);
                }
            }
        }
        LOGGER.info("修改数据状态成功！");
        return xr;
    }
}
